package com.app.signing.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;
import com.app.signing.R;
import java.util.Objects;

public class SigningSettingDialog extends DialogFragment {

    public static SigningSettingDialog newInstance() {
        return new SigningSettingDialog();
    }

    protected NoticeDialogListener dialogListener;

    protected EditText editRange;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            dialogListener = (NoticeDialogListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(
                    context.toString() + " must implement NoticeDialogListener");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getContext()));
        builder.setView(buildCustomView())
                .setTitle(createTitle())
                .setPositiveButton(R.string.determine, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialogListener.onDialogPositiveClick(SigningSettingDialog.this,
                                editRange.getText().toString().trim());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialogListener.onDialogNegativeClick(SigningSettingDialog.this);
                    }
                });
        return builder.create();
    }

    protected String createTitle() {
        return getString(R.string.set_signing_range);
    }

    protected View buildCustomView() {
        View view = Objects.requireNonNull(getActivity())
                .getLayoutInflater()
                .inflate(R.layout.messgae_dialog, null);
        editRange = view.findViewById(R.id.edit_signing_range);
        return view;
    }

    public interface NoticeDialogListener {

        void onDialogPositiveClick(DialogFragment dialog, String value);

        void onDialogNegativeClick(DialogFragment dialog);
    }
}
